<?php
session_start();
require_once 'includes/Security.php';
require_once 'includes/User.php';
require_once 'includes/FileManager.php';

// 初始化安全设置
Security::secureSession();

$user = new User();
$fileManager = new FileManager();

// 检查用户是否已登录
if (!$user->isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$currentUser = $user->getCurrentUser();
$message = '';

// 处理文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $message = '无效的请求';
    } else {
        if (isset($_FILES['file'])) {
            $result = $fileManager->uploadFile($_FILES['file'], $currentUser['id']);
            $message = $result['message'];
        } elseif (isset($_POST['delete_file'])) {
            $result = $fileManager->deleteFile($_POST['file_id'], $currentUser['id']);
            $message = $result['message'];
        }
    }
}

// 获取用户文件列表
$files = $fileManager->getUserFiles($currentUser['id']);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件管理 - 个人文件管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .file-card {
            transition: transform 0.2s;
        }
        .file-card:hover {
            transform: translateY(-5px);
        }
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
        }
        .upload-area:hover {
            border-color: #0d6efd;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">个人文件管理系统</a>
            <div class="navbar-text text-white">
                欢迎，<?php echo Security::sanitizeOutput($currentUser['username']); ?>
            </div>
            <form method="POST" action="index.php" class="d-inline">
                <input type="hidden" name="action" value="logout">
                <button type="submit" class="btn btn-outline-light">退出</button>
            </form>
        </div>
    </nav>

    <div class="container mt-4">
        <?php if ($message): ?>
            <div class="alert alert-info"><?php echo Security::sanitizeOutput($message); ?></div>
        <?php endif; ?>

        <!-- 文件上传区域 -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">上传文件</h5>
                <form method="POST" enctype="multipart/form-data" id="uploadForm">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    <div class="upload-area" id="uploadArea">
                        <i class="fas fa-cloud-upload-alt fa-3x mb-3"></i>
                        <p>点击或拖拽文件到此处上传</p>
                        <input type="file" name="file" id="fileInput" class="d-none" required>
                    </div>
                    <div class="text-center mt-3">
                        <button type="submit" class="btn btn-primary">上传</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 文件列表 -->
        <div class="row">
            <?php foreach ($files as $file): ?>
                <div class="col-md-4 mb-4">
                    <div class="card file-card">
                        <div class="card-body">
                            <h5 class="card-title text-truncate">
                                <?php echo Security::sanitizeOutput($file['original_name']); ?>
                            </h5>
                            <p class="card-text">
                                <small class="text-muted">
                                    大小: <?php echo number_format($file['file_size'] / 1024, 2); ?> KB<br>
                                    类型: <?php echo Security::sanitizeOutput($file['file_type']); ?><br>
                                    上传时间: <?php echo date('Y-m-d H:i', strtotime($file['uploaded_at'])); ?>
                                </small>
                            </p>
                            <div class="d-flex justify-content-between">
                                <a href="download.php?id=<?php echo $file['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-download"></i> 下载
                                </a>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                                    <input type="hidden" name="file_id" value="<?php echo $file['id']; ?>">
                                    <button type="submit" name="delete_file" class="btn btn-sm btn-danger" 
                                            onclick="return confirm('确定要删除这个文件吗？')">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script>
        // 文件上传区域交互
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');

        uploadArea.addEventListener('click', () => fileInput.click());

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#0d6efd';
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '#ccc';
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ccc';
            fileInput.files = e.dataTransfer.files;
        });
    </script>
</body>
</html>